package org.wanho;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Author：汤小洋
 * Date：2023-05-08 15:48
 * Description：<描述>
 */
public class Test06_函数式接口 {

    public static void main(String[] args) {
        /**
         * Consumer 打印传入的参数
         */
        Consumer<String> c = t -> System.out.println(t);
        c.accept("hello");

        /**
         * Supplier 随机返回一个0~99之间的整数
         */
        Supplier<Integer> s = () -> new Random().nextInt(100);
        System.out.println(s.get());

        /**
         * Function  随机返回一个0~t之间的整数
         */
        Function<Integer, Integer> f = t -> new Random().nextInt(t+1);
        System.out.println(f.apply(50));

        /**
         * Predicate 判断整数是否为偶数
         */
        Predicate<Integer> p = t -> t%2==0;
        System.out.println(p.test(18));

        List<String> list = Arrays.asList("aaa","bb","c","dddd","ee","fff");
        // 筛选出长度大于2的字符串
        List<String> newList = strFilter(list, t -> t.length() > 2);
        System.out.println(newList);

    }

    /**
     * 按指定规则过滤字符串，返回过滤后的字符串集合
     */
    public static List<String> strFilter(List<String> list, Predicate<String> filter){
        List<String> newList = new ArrayList<>();
        for(String str : list){
            if(filter.test(str)){ // 过滤
                newList.add(str);
            }
        }
        return newList;
    }



}
